import { Injectable } from '@nestjs/common';
import axios from 'axios';
// import CryptoJS from 'crypto-js';
const CryptoJS = require('crypto-js');
const crypto = require('crypto');
// import FormData from 'form-data';
const FormData = require('form-data');
// import fs from 'fs';
const fs = require('fs');
const https = require('https')

@Injectable()
export class IflytekOcrService {
  private readonly APP_ID = '5ec773ec';
  private readonly API_KEY = '7b7042e5f11130a23d470cf61548764b';
  private readonly API_SECRET = '76ca70ac9eb5cf6f15ceb0b3dbab60d5';
  private readonly OCR_URL = 'https://cbm01.cn-huabei-1.xf-yun.com/v1/private/sf8e6aca1';

  async recognizeImage(imagePath: string) {
    const date = new Date().toUTCString();
    const host = 'api.xf-yun.com';
    const httpMethod = 'POST';
    const apiPath = '/v1/private/sf8e6aca1';
    const digest = this.generateDigest(imagePath);
    // const signatureOrigin = `host: ${host}\ndate: ${date}\n${httpMethod} ${apiPath} HTTP/1.1\ndigest: SHA-256=${digest}`;
    // const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.API_SECRET);
    // const signature = CryptoJS.enc.Base64.stringify(signatureSha);
    // const authorizationOrigin = `api_key="${this.API_KEY}", algorithm="hmac-sha256", headers="host date request-line digest", signature="${signature}"`;
    // const authorization = Buffer.from(authorizationOrigin).toString('base64');

    const signature_orgin= `host: api.xf-yun.com\ndate: ${date}\nPOST /v1/private/sf8e6aca1 HTTP/1.1` 
    let signature=crypto.createHmac('sha256', this.API_SECRET).update(signature_orgin).digest("base64")
    const authorization_origin=`api_key="${this.API_KEY}",algorithm="hmac-sha256",headers="host date request-line",signature="${signature}"`
    const authorization=Buffer.from(authorization_origin).toString('base64')

    // const formData = new FormData();
    // formData.append('image', fs.createReadStream(imagePath));
    // formData.append('header', JSON.stringify({
    //   app_id: this.APP_ID,
    //   status: 3
    // }));

    const submitData = {
        "header": {
          "app_id": this.APP_ID,
          "status": 3
        },
        "parameter": {
          "sf8e6aca1": {
            "category": "ch_en_public_cloud",
            "result": {
              "encoding": "utf8",
              "compress": "raw",
              "format": "json"
            }
          }
        },
        "payload": {
          "sf8e6aca1_data_1": {
            "encoding": "jpg",
            "status": 3,
            "image": fs.readFileSync(imagePath, 'base64')
          }
        }
      }

    try {
        const agent = new https.Agent({  
            rejectUnauthorized: false
          });
      const response = await axios.post(`${this.OCR_URL}?authorization=${authorization}&host=${host}&date=${date}`, JSON.stringify(submitData), {
        headers: {
          'Content-Type': 'application/json',
          'Host': host,
          'app_id': this.APP_ID,
        },
        httpsAgent: agent 
      });
      return response.data;
    } catch (error) {
      console.error('科大讯飞 OCR 请求出错:',error);
      throw error;
    }
  }

  private generateDigest(imagePath: string): string {
    const fileData = fs.readFileSync(imagePath);
    const hash = CryptoJS.SHA256(fileData);
    return hash.toString(CryptoJS.enc.Base64);
  }
}